#include "socketviewer.h"
#include <QThread>
#include <QByteArray>
#include <string.h>

SocketViewer::SocketViewer(const QString _hostName, const quint16 _port, QObject *parent) : QObject(parent)
{
    const char viewer[] = "SocketViewer";
    // 1. 创建TCP套接字对象
    socket = new QTcpSocket(this);
    socket->abort();        //取消原有连接
    // 2. 已连接、数据可读、失败信号连接
    //connect(socket, &QTcpSocket::connected, this, &SocketClient::connected);
    connect(socket, &QIODevice::readyRead, this, &SocketViewer::readyRead);
    typedef void (QAbstractSocket::*QAbstractSocketErrorSignal)(QAbstractSocket::SocketError);
    connect(socket, static_cast<QAbstractSocketErrorSignal>(&QTcpSocket::error), this, &SocketViewer::error);
    //3. 与服务器端建立连接
    //socket->connectToHost("39.108.72.130", 9910, QTcpSocket::ReadWrite);
    socket->connectToHost(_hostName, _port, QTcpSocket::ReadWrite);
    socket->waitForConnected();
    //4. 同步处理-等待数据可读
    //socket->waitForReadyRead();
    socket->write(viewer, strlen(viewer));
    socket->flush();
    socket->waitForBytesWritten();
}

void SocketViewer::connected()
{
    qDebug() << "SocketViewer::readyRead " << socket->readAll();
}

void SocketViewer::readyRead()
{
    qDebug() << "SocketViewer::connected  successfully";
}

void SocketViewer::error(QAbstractSocket::SocketError socketError)
{
    qDebug() << "SocketViewer::error " << socketError;
}

